package com.diy.springframework.step.resource;

import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.ClassLoaderUtil;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;

/**
 * @program: diy_spring
 * @description:
 * @author: CaoYong
 * @create: 2021-07-22 09:41
 **/
public class ClassPathResource implements Resource {

    private final String path;

    private ClassLoader classLoader;

    public ClassPathResource(String path) {
        this(path, null);
    }

    public ClassPathResource(String path, ClassLoader classLoader) {
        Assert.notNull("Path not be null");
        this.path = path;
        this.classLoader = classLoader != null ? classLoader : ClassLoaderUtil.getClassLoader();
    }

    @Override
    public InputStream getInputStream() throws IOException {
        InputStream is = classLoader.getResourceAsStream(path);
        if (is == null) {
            throw new FileNotFoundException(this.path + "not exist");
        }
        return is;
    }
}
